﻿using System;
using System.Linq;
using System.Web;
using WASM.WebSite.DataEntities;
using System.Web.Caching;

namespace WASM.WebSite.Models
{
	public static class AzureStorageUserSettingsRepository
	{
		public static AzureStorage[] List()
		{
			using (WASM_DBDataContext dc = new WASM_DBDataContext())
			{
				return dc.AzureStorages.Where(e => e.UserName == HttpContext.Current.User.Identity.Name).ToArray();
			}
		}

		public static AzureStorage Single(Guid azureStorageId)
		{
			using (WASM_DBDataContext dc = new WASM_DBDataContext())
			{
				return dc.AzureStorages.Where(e => e.AzureStorageId == azureStorageId).Single();
			}
		}

		public static void Update(AzureStorage azureStorage)
		{
			using (WASM_DBDataContext dc = new WASM_DBDataContext())
			{
				AzureStorage azureStorageDataBazse = dc.AzureStorages.Where(e => e.AzureStorageId == azureStorage.AzureStorageId).First();
				azureStorageDataBazse.asKey = azureStorage.asKey;
				azureStorageDataBazse.AzureStorageTypeId = azureStorage.AzureStorageTypeId;
				azureStorageDataBazse.asUrl = azureStorage.asUrl;
				azureStorageDataBazse.asName = azureStorage.asName;
				azureStorageDataBazse.asAccountName = azureStorage.asAccountName;
				azureStorageDataBazse.UserName = azureStorage.UserName ?? HttpContext.Current.User.Identity.Name;

				dc.SubmitChanges();
			}
		}

		public static void Insert(AzureStorage azureStorage)
		{
			using (WASM_DBDataContext dc = new WASM_DBDataContext())
			{
				if (azureStorage.UserName == null)
					azureStorage.UserName = HttpContext.Current.User.Identity.Name;
				if (azureStorage.AzureStorageId == Guid.Empty)
					azureStorage.AzureStorageId = Guid.NewGuid();
				dc.AzureStorages.InsertOnSubmit(azureStorage);
				dc.SubmitChanges();
			}
		}

		public static void Delete(Guid azureStorageId)
		{
			using (WASM_DBDataContext dc = new WASM_DBDataContext())
			{
				AzureStorage azureStorageDataBazse = dc.AzureStorages.Where(e => e.AzureStorageId == azureStorageId).First();
				dc.AzureStorages.DeleteOnSubmit(azureStorageDataBazse);
				dc.SubmitChanges();
			}
		}

		public static AzureStorageType[] AzureStorageTypeList()
		{
			const string cacheKey = "AzureStorageTypeList";
			using (WASM_DBDataContext dc = new WASM_DBDataContext())
			{
				AzureStorageType[] azureStorageTypeList = (AzureStorageType[])HttpRuntime.Cache[cacheKey];
				if (azureStorageTypeList == null)
				{
					azureStorageTypeList = dc.AzureStorageTypes.ToArray();
					HttpRuntime.Cache[cacheKey] = azureStorageTypeList;
				}
				return azureStorageTypeList;
			}
		}

		public static string GetAzureStorageTypeName(int azureStorageTypeId)
		{
			return AzureStorageTypeList().Where(e => e.AzureStorageTypeId == azureStorageTypeId).Select(e => e.astName).First();
		}
	}
}
